package cn.itcast;

import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.function.LongBinaryOperator;
import java.util.stream.LongStream;

public class Test {
    public static void main(String[] args) {
        Instant start = Instant.now();
        long sum =0;
        for (int i = 0; i < 20000000000l; i++) {
            sum+=i;
        }
        System.out.println(sum);
        Instant end = Instant.now();
        //单线程，五百亿求和花费的时间为：
        System.out.println("单线程，五百亿求和花费的时间为："+ Duration.between(start,end).toMillis());

        System.out.println("------------------------------------------------------------");
        //并行流计算
        Instant start1 = Instant.now();
        LongStream longStream = LongStream.rangeClosed(0,20000000000l);
        OptionalLong result = longStream.parallel().reduce(new LongBinaryOperator() {
            @Override
            public long applyAsLong(long left, long right) {
                return left+right;
            }
        });
        System.out.println(result.getAsLong());
        Instant end1 = Instant.now();
        System.out.println("五百亿的求和时间为："+Duration.between(start1,end1).toMillis());

    }
}
